// pages/PersonalCenter/PersonalCenter.js
const util = require("../../utils/util.js");
const config = require("../../utils/config.js")

var app = getApp();
const requestManager = require("../../utils/request.js");
var router = require('../../utils/router.js');
const pageName = "PersonalCenter "

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabbar:true,
    sameEbuyList: [], // 本期内购
    nextEbuyList: [], // 下期内购
    beforeEbuyList: [], // 之前的内购
    day: 0,
    hour: 0,
    minute: 0,
    second: 0,
    // 用于iPhone X适配
    isIpx: app.globalData.isIpx ? true : false,
    openType: "getUserInfo", // button open-type
    phoneNum: "", // 用户当前绑定的手机号
    noticeTitle: "" // 通知标题
  },
  getUserDInfo(e) {
    util.showLoading()
    console.log(e)
    return new Promise(function (outResolve, outReject) {
      getApp().globalData.userInfo = e.detail.userInfo;
      getApp().globalData.isAuthorize = true;
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          // 登录
          getApp().globalData.code = res.code;
          let params = {
            code: getApp().globalData.code,
            appId: config.appId,
            userType: 1,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          }
          requestManager.getDataResult(requestManager.wx_app_login, params, "POST")
            .then(resolve => {
              console.log('resolve.........', resolve)
              getApp().globalData.loginResult = resolve;
              getApp().globalData.userToken = resolve.userToken;
              resolve.target = e.target
              outResolve(resolve)
              requestManager.getDataResult(requestManager.getUserLogin, {
                userId: resolve.userId,
                mobile: resolve.mobile
              }, "POST").then(res1 => {
                console.log(res1)
                // 企业Id
                app.globalData.enterpriseId = res1.enterpriseId
              }).catch(err => {
                console.log(err)
                if (resolve.mobile !== '') {
                  app.globalData.enterpriseId = '-1' // 如果手机号没有内购权限
                  util.noIconToast(err.msgContent, 3000)
                } else {
                  resolve.enterpriseId = '-2' // 请先去绑定手机号
                  util.noIconToast('请先绑定手机号!', 3000)
                }
              })
              wx.setStorage({
                key: 'loginResult',
                data: resolve,
              })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (getApp().loginResultReadyCallback) {
                getApp().loginResultReadyCallback(resolve)
              }
              wx.hideLoading()
            }, reject => {
              wx.hideLoading()
            })
        },
        fail: res => {
          outReject(res)
          wx.hideLoading()
        }
      })
    })
  },
  // 初始化进来 点击我知道按钮
  gotoUserInfo(e){
    this.getUserDInfo(e).then(res => {
      wx.setStorage({
          key: 'tabbar',
          data: true
      })
      this.setData({
        tabbar:false
      },()=>{
        wx.showTabBar()
      })
      wx.hideLoading()
    }).catch(err => {
      this.getUserDInfo(e)
      wx.hideLoading()
      wx.setStorage({
          key: 'tabbar',
          data: true
      })
      this.setData({
        tabbar:false
      },()=>{
        wx.showTabBar()
      })
    })
  },
  onGotUserInfo(e) {
    this.getUserDInfo(e).then(res => {
      console.log(res)
    }).catch(err => {
      this.getUserDInfo(e)
    })
  },
  // 订单详情跳转到
  goOrderlist(e) {
    this.getUserDInfo(e).then(res => {
      if (res.target.id == 'order') {
        let url = "/pages/orderList/orderList";
        router.route.setAction(router.NAVIGATE_TO)
          .setParams([])
          .setUrl(url)
          .run()
      }
    }).catch(err => {
      this.getUserDInfo(e)
    })
  },
  goGoodsInfo(e) {
    // 跳转到商品详情
    this.getUserDInfo(e).then(res => {
      console.log(res)
      let url = "/pages/goodsInfo/goodsInfo";
      router.route.setAction(router.NAVIGATE_TO)
        .setParams([`productId=${e.target.dataset.productid}&ebuyId=${e.target.dataset.ebuyid}&isCart=${e.target.dataset.iscart}`])
        .setUrl(url)
        .run()
    }).catch(err => {
      this.getUserDInfo(e)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tabbar = wx.getStorageSync('tabbar')
    if(tabbar){
      this.setData({
        tabbar:false
      },()=>{
        wx.showTabBar()
      })
    }else{
      this.setData({
        tabbar:true
      },()=>{
        wx.hideTabBar()
      })
    }
    // 头像及微信名获取的回调
    app.userInfoReadyCallback = res => {
      this.setData({
        wxUserInfo: res.userInfo,
      })
    };

    //获取头像
    if (app.globalData.userInfo) {
      this.setData({
        wxUserInfo: app.globalData.userInfo,
      })
    };

    // 显示绑定的手机号(获取用户微信信息通常为异步的,因此这里不会出现频繁setData的问题)
    this.data.phoneNum = util.getUserInfo().mobile;
    if (this.data.phoneNum != "") {
      this.setData({
        phoneNum: this.data.phoneNum,
      })
    };
    app.loginResultReadyCallback = res => {
      // 用户登录成功的回调
      this.setData({
        phoneNum: res.mobile,
      })
    };
    // 获取商品列表
    console.log('getUserInfo_____存在变量里面的公共变量', util.getUserInfo())
    let params = {
      userId: util.getUserInfo().userId,
      channel: 'wxapp'
    }

    requestManager.getDataResult(requestManager.product_list, params, "GET").then(res => {
      console.log('商品列表接口数据...', res)
      let sameData = []
      let nextData = []
      let beforeData = []
      // 只有内购有购物车图标
      res.sameEbuy.isCart = 1
      res.nextEbuy.isCart = 2
      res.beforeEbuy.isCart = 3
      sameData.push(res.sameEbuy)
      nextData.push(res.nextEbuy)
      beforeData.push(res.beforeEbuy)
      console.log('sameData...', sameData)
      console.log('nextData...', nextData)
      this.setData({
        sameEbuyList: sameData,
        nextEbuyList: nextData,
        beforeEbuyList: beforeData
      })
      setTimeout(() => {
        requestManager.getDataResult(requestManager.getUserLogin, {
          userId: util.getUserInfo().userId,
          mobile: util.getUserInfo().mobile
        }, "POST").then(res => {
          console.log(res)
          // 企业Id
          app.globalData.enterpriseId = res.enterpriseId
        }).catch(err => {
          console.log(err)
          if (util.getUserInfo().mobile !== '') {
            app.globalData.enterpriseId = '-1' // 如果手机号没有内购权限
            util.noIconToast(err.msgContent, 3000)
          } else {
            app.globalData.enterpriseId = '-2' // 请先去绑定手机号
            util.noIconToast('请先绑定手机号!', 3000)
          }
        })
      }, 1000)
      this.countDown(res.nextEbuy.endTime)
    })
  },
  // 倒计时
  countDown(options) {
    var timer = null;
    let obj = this
    var day = 0,
      hour = 0,
      minute = 0,
      second = 0; //时间默认值
    var tTimer
    // var tTimer = times - parseInt(new Date().getTime() / 1000)
    timer = setInterval(function () {
      tTimer = options - parseInt(new Date().getTime() / 1000)

      if (tTimer > 0) {
        day = Math.floor(tTimer / (60 * 60 * 24));
        hour = Math.floor(tTimer / (60 * 60)) - (day * 24);
        minute = Math.floor(tTimer / 60) - (day * 24 * 60) - (hour * 60);
        second = Math.floor(tTimer) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
      }
      if (day <= 9 && day > 0) day = '0' + day;
      if (hour <= 9 && hour > 0) hour = '0' + hour;
      if (minute <= 9 && minute > 0) minute = '0' + minute;
      if (second <= 9 && second > 0) second = '0' + second;
      //
      obj.setData({
        day: day,
        hour: hour,
        minute: minute,
        second: second

      })
      // console.log(day + "天:" + hour + "小时：" + minute + "分钟：" + second + "秒");
      // times--;
    }, 1000);
    if (tTimer <= 0) {
      clearInterval(timer);
    }
  },
  onShow: function () {
    // 获取通知内容
    this._getNoticeContent();

    if (app.globalData.isShowBack) {
      app.globalData.isShowBack = false;
    };

    if (this.data.phoneNumChanged == true) {
      this.data.phoneNumChanged = false;
      // 用户重新绑定了手机
      this.setData({
        phoneNum: this.data.phoneNum,
      })
    };
  },

  /**
   * 获取通知详情
   */
  _getNoticeContent: function () {
    let params = {
      channel: "wxapp"
    };
    requestManager.getDataResult(requestManager.notice_latest, params, "GET")
      .then(data => {
        let noticeId = data.noticeId;
        if (noticeId != undefined && noticeId != null && noticeId != 0) {
          this.data.noticeId = noticeId;
          this.setData({
            noticeTitle: data.noticeTitle
          });
        } else {
          this.setData({
            noticeTitle: ""
          });
        }
      }).catch(e => {

      });
  },

  //跳转绑卡
  jumpBindCard: function (sender) {
    let self = this;
    //读取登录信息
    if (!app.globalData.isAuthorize) {
      this.setData({
        openType: "getUserInfo"
      });
      return;
    } else if (this.data.openType != "") {
      this.setData({
        openType: ""
      });
    }
    //执行页面跳转
    if (sender.currentTarget.id == 1) {
      console.log("11111111")

    } else if (sender.currentTarget.id == 2) {

    } else if (sender.currentTarget.id == 3) {

    } else if (sender.currentTarget.id == 4) {
      //个人设置
      let url = "/pages/MyHomePage/MyHomePage";
      router.route.setAction(router.NAVIGATE_TO)
        .setReportName("SettingPayAccount")
        .setUrl(url)
        .run();

      util.reportAnalytics("to_Setting_account");
      console.log("44444")

    }

  },

  /**
   * 去公告中心
   */
  toNoticeCenter: function () {
    let url = "/pages/NoticeCenter/NoticeCenter";
    let params = ["noticeId"];
    if (this.data.noticeId == undefined || this.data.noticeId == null) {
      params.push("0");
    } else {
      params.push(this.data.noticeId);
    }
    router.route.setAction(router.NAVIGATE_TO)
      .setReportName("NoticeCenter")
      .setParams(params)
      .setUrl(url)
      .run();
  },

  /**
   * 绑定手机号
   */
  bindPhoneNum: function (e) {
    if (!app.globalData.isAuthorize) {
      this.setData({
        openType: "getUserInfo"
      });
      return;
    } else if (this.data.openType != "") {
      this.setData({
        openType: ""
      });
    }
    let url = "/pages/PhoneVerificationPage/PhoneVerificationPage";
    router.route.setAction(router.NAVIGATE_TO)
      .setReportName("PhoneVerificationPage")
      .setUrl(url)
      .run();
  },

  /**
   * 联系客服
   */
  callServiceOnline: function () {
    util.reportAnalytics("call_service_online_home");
  },

  /**
   * 表单的相关处理
   */
  formSubmit: util.formSubmit,

  /**
   * 为确保用户授权获取头像信息的回调函数
   */
  getUserInfo: function (e) {
    if (app.globalData.isAuthorize || !e.detail.userInfo) {
      return;
    };

    util.userLogin().then(function () { }, reject => {
      setTimeout(function () {
        util.userLogin();
      }, 1000);
    });

    app.globalData.userInfo = e.detail.userInfo;
    app.globalData.isAuthorize = true;
    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    this.setData({
      wxUserInfo: e.detail.userInfo,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return {
      path: '/pages/PersonalCenter/PersonalCenter',
      imageUrl: 'https://bn.t.ivision.vip/static/image/wls/tag.png',
      // imageUrl: 'https://vls.t.ivision.vip/static/image/wls/tag.png',
      title: "微礼说，礼尚往来新方式。让心意更动人，送礼更方便。"
    }
  }
})